<?php
require('class_ws.php');
$ws = new Ws('0.0.0.0', '7000', 10000);
$ws->function['add'] = 'user_add_callback';
$ws->function['send'] = 'send_callback';
$ws->function['close'] = 'close_callback';
$ws->start_server();

//回调函数们
function user_add_callback($ws) {
	$data = count($ws->accept);
// 	send_to_all($data, 'num', $ws);
}

function close_callback($ws) {
	$data = count($ws->accept);
//	send_to_all($data, 'num', $ws);
}

function send_callback($data, $index, $ws) {
//    if(check_utf8($data)){
//        $data = json_encode(array(
//            'text' => $data,
//            'user' => $index
//        ));
//        send_to_all($data, 'text', $ws);
//    }
}

function send_to_all($data, $type, $ws){
	$res = array(
			'msg' => $data,
			'type' => $type
			);
	$res = json_encode($res);
	$res = $ws->frame($res);
	foreach ($ws->accept as $key => $value) {
		socket_write($value, $res, strlen($res));
	}
}

function check_utf8($str)
{
    $len = strlen($str);
    for($i = 0; $i < $len; $i++){
        $c = ord($str[$i]);
        if ($c > 128) {
            if (($c > 247)) return false;
            elseif ($c > 239) $bytes = 4;
            elseif ($c > 223) $bytes = 3;
            elseif ($c > 191) $bytes = 2;
            else return false;
            if (($i + $bytes) > $len) return false;
            while ($bytes > 1) {
                $i++;
                $b = ord($str[$i]);
                if ($b < 128 || $b > 191) return false;
                $bytes--;
            }
        }
    }
    return true;
}